#!/usr/bin/env bash

LC_CTYPE=C
master_m3u="$1"
v_name="$2"

__usage() {
    echo "usage: ph1080 <master_m3u_URL>"
    exit 1
}


m3u_base_url=$(echo "$master_m3u" | rev | cut -d '/' -f2-10 | rev)
m3u_init_index=$(wget -U mozilla --no-cookie "$master_m3u" -qO- /dev/null \
                   | grep -E "index-f1")
R_N=$(tr -dc '0-9' < /dev/urandom | head -c 9)
ts_segment_list="${m3u_base_url}/${m3u_init_index}"


main()
{

    #
    # input_check
    #
    
    [ -z "$(echo "$master_m3u" |  grep 'master.m3u')" ] && __usage || :
	
 	#
	# Create random directory for video
	#

	mkdir -p ./"$R_N"

	#
	# Generate the list of .ts file segments
	#

	wget -U -mozilla "$ts_segment_list" -qO- /dev/null | grep seg \
		| sed "s|^|${m3u_base_url}/|g" \
		> ./"$R_N"/"$R_N".m3u8

	#
	# Download the .ts files with aria
	#

	aria2c -x16 -k1M -i ./"$R_N"/"$R_N".m3u8 -d ./"$R_N"

	#
	# Join the .ts files
	#

	cat ./"$R_N"/*.ts > ./"$R_N"/out.ts

	#
	# Join the .ts files into .mp4 video
	#

	[ -z "$v_name" ] && ffmpeg -i ./"$R_N"/out.ts -codec copy ./"$R_N".mp4 \
    	|| ffmpeg -i ./"$R_N"/out.ts -codec copy ./"$v_name".mp4

	#
	# Remove the temporary directory
	#

	rm -rf ./"$R_N"
}

#
# Main function
#

main